<template>
  <view class="app-page">
    <view class="file-content">
      <view v-if="info.contractState == 0" class="title">
        邀请{{
          (ownRoleType === 0 && info.creditorMember) ||
          (ownRoleType === 1 && info.debtorMember)
            ? "对方"
            : "您"
        }}填写借条
      </view>
      <view v-else-if="info.contractState == 1" class="title">
        邀请{{
          (ownRoleType === 0 && info.creditorMemberSignatureId) ||
          (ownRoleType === 1 && info.debtorMemberSignatureId)
            ? "对方"
            : "您"
        }}签署借条
      </view>
      <view v-else-if="info.contractState == 2" class="title">
        借条已签署
      </view>
      <view v-else-if="info.contractState == 3" class="title">
        借条已撤回
      </view>
      <view v-else-if="info.contractState == 4" class="title">
        借条已拒签
      </view>
      <view v-else-if="info.contractState == 5" class="title">
        借条已失效
      </view>
      <view v-else class="title"></view>
      <view class="tip">
        {{
          info.contractState < 2
            ? `请于${info.expirationTime || "-"}前完成签署借条`
            : ""
        }}
      </view>
      <view class="item">
        <view class="label"> 出借人: </view>
        <view class="value">
          {{ info.creditorMember ? info.creditorMemberName : "待授权信息" }}
        </view>
      </view>
      <view class="item">
        <view class="label"> 借款人: </view>
        <view class="value">
          {{ info.debtorMember ? info.debtorMemberName : "待授权信息" }}
        </view>
      </view>
      <view class="item">
        <view class="label"> 借款金额: </view>
        <view class="value price">
          {{ info.loanAmount ? info.loanAmount : "-" }}元
        </view>
      </view>
      <view class="item">
        <view class="label"> 借款时间: </view>
        <view class="value">
          {{ info.debtorTime || "-" }} 至 {{ info.repaymentTime || "-" }}
        </view>
      </view>
      <view class="item">
        <view class="label"> 借款用途: </view>
        <view class="value">
          {{ info.borrowingReason || "-" }}
        </view>
      </view>
    </view>
    <view class="btn" @click="handleView"> 查看详情 </view>
    <!-- 购买签署流量弹层 -->
    <pay-flow ref="payFlowRef" @onPay="handlePayFlow" />
    <!-- 购买签署流量弹层 -->
  </view>
</template>

<script>
import {
  apiContractById,
  apiExpiringSoonOne,
  apiMemberSignPackagePay,
  apiBind,
} from "@/api/common.js";
import { getCardStateTxt } from "@/utils/filters";
import {
  parseTime,
  upload,
  ageCheck,
  throttle,
  toThousandFilter,
} from "@/utils/common";
import code2Enum from "@/utils/code2Enum";
import payFlow from "@/components/payFlow/payFlow";
export default {
  components: { payFlow },
  data() {
    return {
      contractId: "",
      userInfo: {},
      info: {},
      contractTemplateId: 2,
      ownRoleType: 0,
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo;
    },
  },
  onLoad(query) {
    uni.hideShareMenu();
    const { contractId } = query;
    this.contractId = contractId;
    this.getData();
  },
  onPullDownRefresh() {
    uni.showLoading();
    this.getData();
  },
  methods: {
    getData() {
      const { memberId } = this.userInfo;
      apiContractById({
        contractId: this.contractId,
      })
        .then((res) => {
          uni.hideLoading();
          uni.stopPullDownRefresh();
          if (res.code === 200) {
            res.data = {
              ...res.data,
              loanAmount: toThousandFilter(
                (res.data.loanAmount / 100).toFixed(2)
              ),
              contractState: code2Enum.contractStateEnum(
                res.data.contractState
              ),
              promoterType: code2Enum.promoterTypeEnum(res.data.promoterType),
              contractPayState: code2Enum.contractPayStateEnum(
                res.data.contractPayState
              ),
              paymentType: code2Enum.paymentTypeEnum(res.data.paymentType),
              transferStatus: code2Enum.transferStatusEnum(
                res.data.transferStatus
              ),
            };
            const {
              creditorMember,
              creditorMemberSignatureId,
              debtorMember,
              debtorMemberSignatureId,
            } = res.data;
            this.info = {
              ...res.data,
              fileState: getCardStateTxt(res.data),
              debtorUserSignState: debtorMemberSignatureId
                ? "yqs"
                : debtorMember
                ? "ytx"
                : "dtx",
              creditorMemberSignState: creditorMemberSignatureId
                ? "yqs"
                : creditorMember
                ? "ytx"
                : "dtx",
              expirationTime: parseTime(
                res.data.expirationTime,
                "{m}月{d}日 {h}:{i}分"
              ),
            };
            this.ownRoleType =
              memberId === creditorMember
                ? 0
                : debtorMember === memberId
                ? 1
                : 2;
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.stopPullDownRefresh();
        });
    },
    // 详情
    handleView: throttle(function () {
      const _this = this;
      const contractId = _this.contractId;
      // 查询合同状态
      apiContractById({
        contractId: contractId,
      }).then((res) => {
        if (res.code === 200) {
          res.data = {
            ...res.data,
            contractState: code2Enum.contractStateEnum(res.data.contractState),
            promoterType: code2Enum.promoterTypeEnum(res.data.promoterType),
            contractPayState: code2Enum.contractPayStateEnum(
              res.data.contractPayState
            ),
            paymentType: code2Enum.paymentTypeEnum(res.data.paymentType),
            transferStatus: code2Enum.transferStatusEnum(
              res.data.transferStatus
            ),
          };
          // 授权信息
          _this.$store.dispatch("ASYNC_LOGIN", (userInfo) => {
            console.log(userInfo, "userInfo");
            const { memberId } = userInfo;
            const {
              debtorMember,
              creditorMember,
              contractState,
              memberSignPackageId,
              creditorMemberSignatureId,
              debtorMemberSignatureId,
            } = res.data;
            //roleType  0  出借方  1  借款方  2 第三方
            let roleType = 2;
            // 判断当前合同状态
            // 1.乙方未填写
            if (contractState === 0) {
              // 年龄验证
              const check = ageCheck(userInfo.memberIdNumber);
              if (!check) {
                uni.showModal({
                  title: "提示",
                  content:
                    "为减少用户签订借条时产生的纠纷，签鸽仅向22-75岁的中国大陆公民提供电子借条服务。",
                  showCancel: false,
                  confirmText: "我知道了",
                });
                return false;
              }
              if (creditorMember) {
                roleType = memberId === creditorMember ? 0 : 1;
              } else {
                roleType = memberId === debtorMember ? 1 : 0;
              }
              // 是否支付 memberSignPackageId 流量包id
              // 已支付
              if (memberSignPackageId) {
                // 甲方
                if (memberId === creditorMember || memberId === debtorMember) {
                  uni.navigateTo({
                    url: `/pages/fileState/fileState?contractId=${contractId}&roleType=${roleType}`,
                  });
                } else {
                  //乙方  需绑定

                  _this.bind2User(roleType);
                }
              } else {
                //未支付

                // 借款方必须付款--
                if (roleType === 1) {
                  // 是否剩余流量包
                  apiExpiringSoonOne().then((response) => {
                    if (response.code === 200) {
                      const hasPackageId = response.data
                        ? response.data.memberSignPackageId
                        : null;
                      // 借款方必须支付
                      // 有剩余流量包
                      if (hasPackageId) {
                        uni.showModal({
                          title: "提示",
                          content: "是否使用流量包支付？",
                          cancelText: "取消",
                          cancelColor: "#333",
                          confirmText: "确认",
                          showCancel: true,
                          success: function (result) {
                            console.log(result, "result");
                            if (result.confirm) {
                              // 调用支付接口
                              apiMemberSignPackagePay({
                                contactInfoId: contractId,
                                memberSignPackageId: hasPackageId,
                              })
                                .then((res2) => {
                                  if (res2.code === 200) {
                                    uni.showToast({
                                      content: "借条支付成功",
                                      mask: true,
                                      duration: 2000,
                                    });
                                    _this.bind2User(1);
                                    // setTimeout(() => {
                                    //   // my.navigateTo({
                                    //   //   url: `/pages/create/index?contractId=${contractId}&roleType=${roleType}`
                                    //   // })
                                    // }, 2000)
                                  } else {
                                    uni.showToast({
                                      content: res2.msg,
                                      mask: true,
                                    });
                                  }
                                })
                                .catch((err) => {
                                  if (err.code == 600) {
                                    _this.getData();
                                  }
                                });
                            } else {
                            }
                          },
                          fail: function (err) {
                            console.log(err);
                          },
                        });
                      } else {
                        // 没有剩余流量包 唤起支付购买
                        // uni.showToast({
                        //   content: '余额不足，请充值',
                        //   icon: 'none',
                        //   duration: 2000
                        // })
                        // setTimeout(() => {
                        _this.$refs.payFlowRef.handleOpen();
                        // }, 2000)
                      }
                    }
                  });
                } else {
                  //填写中未支付合同 出借方进入邀请
                  // _this.bind2User(0)
                  uni.navigateTo({
                    url: `/pages/fileState/fileState?contractId=${contractId}&roleType=${roleType}`,
                  });
                }
              }
            } else if (contractState === 1) {
              roleType = _this.ownRoleType;
              // 2.乙方已填写，签署中
              // 2.1 第三方进入
              if (roleType === 2) {
                uni.alert({
                  title: "亲",
                  content: "该合同正在签署中...",
                  buttonText: "我知道了",
                  success: () => {
                    my.reLaunch({
                      url: `/pages/home/index`,
                    });
                  },
                });
              } else {
                // 2.2 甲乙方进入 -- 进入借条页面 去签署合同
                // 2.2.1 出借方
                if (roleType === 0) {
                  // 已签署
                  if (creditorMemberSignatureId) {
                    uni.navigateTo({
                      url: `/pages/fileState/fileState?contractId=${contractId}&roleType=${roleType}`,
                    });
                  } else {
                    // 未签署
                    uni.navigateTo({
                      url: `/pages/borrowFile/borrowFile?contractId=${contractId}&roleType=${roleType}`,
                    });
                  }
                } else if (roleType === 1) {
                  // 已签署
                  if (debtorMemberSignatureId) {
                    uni.navigateTo({
                      url: `/pages/fileState/fileState?contractId=${contractId}&roleType=${roleType}`,
                    });
                  } else {
                    // 未签署
                    uni.navigateTo({
                      url: `/pages/borrowFile/borrowFile?contractId=${contractId}&roleType=${roleType}`,
                    });
                  }
                }
              }
            } else {
              // 3.已生效 失效 取消 拒签
              // 3.1 第三方进入 查看借条
              if (roleType === 2) {
                uni.navigateTo({
                  url: `/pages/orderDetail/orderDetail?contractId=${contractId}&roleType=${roleType}`,
                });
              } else {
                // 3.2 甲乙方进入 -- 进入合同详情页面
                uni.navigateTo({
                  url: `/pages/orderDetail/orderDetail?contractId=${contractId}&roleType=${roleType}`,
                });
              }
            }
          });
        }
      });
    }, 1000),
    // 立即购买流量--借款人调用
    async handlePayFlow() {
      // TODO
      const _this = this;
      _this.$refs.payFlowRef.handleClose();
      const contractId = _this.contractId;
      // 支付合同后  绑定乙方
      apiExpiringSoonOne().then((response) => {
        if (response.code === 200) {
          const memberSignPackageId = response.data
            ? response.data.memberSignPackageId
            : null;
          if (memberSignPackageId) {
            apiMemberSignPackagePay({
              contactInfoId: contractId,
              memberSignPackageId,
            }).then((res2) => {
              if (res2.code === 200) {
                uni.showToast({
                  content: "借条支付成功",
                  mask: true,
                  duration: 2000,
                });
                _this.bind2User(1);
              } else {
                uni.showToast({
                  content: res2.msg,
                  mask: true,
                });
              }
            });
          }
        }
      });
    },
    // 绑定乙方
    bind2User(roleType) {
      const { userInfo, contractId, contractTemplateId } = this;
      let applyData = {};
      if (roleType == 0) {
        applyData = {
          creditorMemberIdNumber: userInfo.memberIdNumber, //借款人身份证号
          creditorMemberName: userInfo.memberName, //借款人姓名
          creditorMemberPhone: userInfo.memberPhone, //借款人手机号
          creditorMember: userInfo.memberId,
        };
      } else {
        applyData = {
          debtorMemberIdNumber: userInfo.memberIdNumber, //借款人身份证号
          debtorMemberName: userInfo.memberName, //借款人姓名
          debtorMemberPhone: userInfo.memberPhone, //借款人手机号
          debtorMember: userInfo.memberId,
        };
      }
      apiBind({
        ...applyData,
        contractId,
        contractTemplateId,
      })
        .then((resultRes) => {
          if (resultRes.code === 200) {
            uni.hideToast();
            uni.redirectTo({
              url: `/pages/borrowFile/borrowFile?contractId=${contractId}&mode=second&roleType=${roleType}`,
            });
          }
        })
        .catch((err) => {
          if (err.code == 600) {
            this.getData();
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-page {
  width: 750rpx;
  height: 100vh;
  overflow-y: auto;
  background: linear-gradient(180deg, #94cefd 0%, #cae7ff 46%, #eef7ff 100%);
  box-sizing: border-box;

  .file-content {
    width: 702rpx;
    height: 1024rpx;
    margin: 208rpx auto 0;
    padding: 81rpx 36rpx 9rpx;
    box-sizing: border-box;
    background-image: url(../../images/pleaseBg.png);
    background-repeat: no-repeat;
    background-size: contain;
    .title {
      height: 78rpx;
      font-size: 56rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #ffffff;
      text-align: center;
      line-height: 78rpx;
    }
    .tip {
      height: 37rpx;
      font-size: 26rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #e3efff;
      text-align: center;
      line-height: 37rpx;
      margin-bottom: 45rpx;
      padding-bottom: 32rpx;
    }
    .item {
      height: 42rpx;
      font-size: 30rpx;
      font-family: PingFangSC, PingFang SC;
      line-height: 42rpx;
      display: flex;
      align-items: center;
      margin-top: 32rpx;
      padding-left: 24rpx;
      box-sizing: border-box;
      .label {
        color: #999999;
        width: 150rpx;
      }
      .value {
        color: #333333;
      }
      .price {
        color: #ff3141;
      }
    }
  }
  .btn {
    width: 654rpx;
    height: 98rpx;
    font-size: 36rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #ffffff;
    line-height: 98rpx;
    background: linear-gradient(180deg, #1c54e7 0%, #367dff 50%, #1677ff 100%);
    border-radius: 49rpx;
    text-align: center;
    margin: 64rpx auto 162rpx;
  }
}
</style>
